import { DrawInteractor } from "./drawInteractor";
import EllipseNodeGraph from "../shape/ellipse";
import { getScale } from "@/graphviewState";
export class EllipseDrawInteractor extends DrawInteractor {
  startPoint: { x: number; y: number } = { x: 0, y: 0 };
  currentPoint: { x: number; y: number } = { x: 0, y: 0 };
  drawing: boolean = false;
  ctx: CanvasRenderingContext2D | null;
  isFill = true;
  constructor(target: HTMLCanvasElement) {
    super(target);
    this.ctx = this.target.getContext("2d");
  }
  handleMouseDown(e: MouseEvent) {
    this.drawing = true;
    this.startPoint.x = e.offsetX;
    this.startPoint.y = e.offsetY;
  }
  handleMouseUp(e: MouseEvent) {
    this.handleMouseMove(e);
    this.drawing = false;
    this.drawEnd();
  }
  handleMouseMove(e: MouseEvent) {
    if (this.drawing) {
      this.currentPoint.x = e.offsetX;
      this.currentPoint.y = e.offsetY;
      this.reDraw();
    }
  }
  reDraw() {
    if (this.ctx) {
      this.emit("redraw");
      this.draw();
    }
  }
  draw() {
    if (this.ctx) {
      this.ctx.restore();
      this.ctx.fillStyle = "rgb(64,158,255)";
      const width = Math.abs(this.currentPoint.x - this.startPoint.x);
      const height = Math.abs(this.currentPoint.y - this.startPoint.y);
      const centerx = (this.currentPoint.x + this.startPoint.x) / 2;
      const centery = (this.currentPoint.y + this.startPoint.y) / 2;
      this.ctx.beginPath();
      this.ctx.ellipse(
        centerx,
        centery,
        width / 2,
        height / 2,
        0,
        0,
        2 * Math.PI
      );
      if (this.isFill) {
        this.ctx.fill();
      } else {
        this.ctx.stroke();
      }
    }
  }
  drawEnd() {
    if (
      this.currentPoint.x === this.startPoint.x &&
      this.currentPoint.y === this.startPoint.y
    ) {
      // 只是在原点点击了一下,不会进行绘制
      return;
    }
    const ellipse = new EllipseNodeGraph();
    // 去除缩放对鼠标获取点坐标的影响
    const scale = getScale();
    ellipse.center = {
      x: (this.currentPoint.x + this.startPoint.x) / (2 * scale),
      y: (this.currentPoint.y + this.startPoint.y) / (2 * scale),
    };
    const width = Math.abs(this.currentPoint.x - this.startPoint.x) / scale;
    const height = Math.abs(this.currentPoint.y - this.startPoint.y) / scale;
    ellipse.radius.x = width / 2;
    ellipse.radius.y = height / 2;
    ellipse.setOriginRect(this.startPoint.x, this.startPoint.y, width, height);
    this.emit("drawend", ellipse);
  }
}
